<script setup lang="ts">
import { useUserStore } from '@renderer/store/modules/user'
import { WebviewTag } from 'electron'
import { storeToRefs } from 'pinia'
import { onMounted, ref, shallowRef } from 'vue'

const visible = defineModel<boolean>('webviewVisible')

const userStore = useUserStore()

const { getUserToken } = storeToRefs(userStore)

const webViewUrl = shallowRef(
  'https://qiguanbang.com/designListPage/658ea19ed3bb4b18a67dfc6c?title=%E6%AF%8F%E6%97%A5%E5%B7%A5%E4%BD%9C%E6%B1%87%E6%8A%A5'
)

const refWebView = ref<WebviewTag>()

onMounted(() => {
  // dom 加载成功
  refWebView.value?.addEventListener('dom-ready', () => {
    // 设置cookie
    refWebView.value?.executeJavaScript(
      `
        document.cookie = "USER_ACCESS_TOKEN=${getUserToken.value};"
        document.cookie = "token=${getUserToken.value};"
      `
    )
  })

  // dom 加载完毕
  refWebView.value?.addEventListener('did-stop-loading', () => {
    // 删除冗余的dom
    refWebView.value?.executeJavaScript(
      `
        timer1 = setInterval(() => {
          // 删除冗余的header
          const dom = document.querySelector(".header")
          if (dom) {
            dom.remove()
            clearInterval(timer1)
            timer1 = null
          }
        }, 1000)

        timer2 = setInterval(() => {
          // 删除冗余的左侧菜单
          const dom = document.querySelector(".main-left-nav")
          if (dom) {
            dom.remove()
            clearInterval(timer2)
            timer2 = null
          }
        }, 1000)

        timer3 = setInterval(() => {
          // 删除冗余的顶部tab
          const dom = document.querySelector(".tagsbox")
          if (dom) {
            dom.remove()
            clearInterval(timer3)
            timer3 = null
          }
        }, 1000)

        timer4 = setInterval(() => {
          // 删除冗余的顶部tab
          const dom = document.querySelector(".container-header")
          if (dom) {
            dom.remove()
            clearInterval(timer4)
            timer4 = null
          }
        }, 1000)

        timer5 = setInterval(() => {
          // 删除冗余的顶部tab
          const dom = document.querySelector(".container-footer")
          if (dom) {
            dom.remove()
            clearInterval(timer5)
            timer5 = null
          }
        }, 1000)
      `
    )
  })
})
</script>

<template>
  <t-drawer
    v-model:visible="visible"
    :show-overlay="false"
    header="提交日报"
    destroy-on-close
    size="50%"
  >
    <div h-full>
      <webview ref="refWebView" border="1px solid #ccc" w-full h-full :src="webViewUrl"> </webview>
    </div>
    <template #footer>
      <div flex justify-center>
        <t-button>确定</t-button>
        <t-button variant="outline" @click="visible = false"> 取消 </t-button>
      </div>
    </template>
  </t-drawer>
</template>

<style scoped></style>
